#include "photon_map.hpp"

Photon_Map::Photon_Map(void) { 
	kd_tree = new Kd_Tree();
	
	Kd_Node* kd_node = new Kd_Node(0.0,0);
	kd_tree->root = kd_node;
	
}

Photon_Map::~Photon_Map(void) { 
	delete kd_tree;
}


void Photon_Map::insert(Photon* _photon) {
	photon_list.push_back(_photon);
}

Kd_Tree* Photon_Map::construct_kd_tree_rec(void) {
	kd_tree->root = construct_kd_tree(0,photon_list.size(),1);
	return kd_tree;
	
}

Kd_Node* Photon_Map::construct_kd_tree(unsigned int _p,unsigned int _q,unsigned int _order) {
	if(photon_list.empty() == false) {
		sort(photon_list.begin(),photon_list.end(),compare);
		/* Choose the median */		
		unsigned int median = floor(photon_list.size()/2);
		Photon* photon = photon_list[median];

			
		double value = 0.0;
		switch(_order) {
			case 1: { 
				value = photon->get_position().x;
				break;
			}
			case 2: {
				value = photon->get_position().y;
				break;
				
			}
			case 3: {
				value = photon->get_position().z;
				break;
			}
		}
		
		
		Kd_Node* node = new Kd_Node(value,Photon::get_order());
		node->add_photon(photon);

		photon_list.erase( photon_list.begin() + median );
		/*Temp*/
			if(_order != 3) _order++;
			else _order = 1;
		/**/
		cout << photon_list.size() << endl;
		node->add_left(construct_kd_tree(_p,median-1,_order));
		node->add_right(construct_kd_tree(median+1,_q,_order));
	}
	return NULL;
	
}
